package com.cuitrip.business.home.travel.ui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cuitrip.apiservice.TrackBusiness;
import com.cuitrip.app.MainApplication;
import com.cuitrip.business.home.favorite.FavoriteListFragment;
import com.cuitrip.business.home.favorite.TravelTrip;
import com.cuitrip.business.home.favorite.proxy.FavProxy;
import com.cuitrip.business.home.favorite.ui.FavAnimation;
import com.cuitrip.business.home.recommend.model.RecommendTravelTrip;
import com.cuitrip.business.home.travel.TravelTripListFragment;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.login.proxy.LoginProxy;
import com.cuitrip.business.track.TrackProxy;
import com.cuitrip.business.tripservice.ServiceDetailActivity;
import com.cuitrip.business.tripservice.proxy.PriceProxy;
import com.cuitrip.component.Label;
import com.cuitrip.component.LabelView;
import com.cuitrip.resource.DrawableClass;
import com.cuitrip.resource.ResourceManager;
import com.cuitrip.service.R;
import com.cuitrip.util.ResourceUtil;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.analytics.ecommerce.Product;
import com.google.android.gms.analytics.ecommerce.ProductAction;
import com.lab.adapter.BaseHolderView;
import com.lab.adapter.IAdapterData;
import com.lab.utils.ImageHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;


/**
 * travel trip的holderview
 * Created by ak
 */
public class TravelTripHolderView extends BaseHolderView {

    @Bind(R.id.service_img)
    public ImageView serviceImg;
    @Bind(R.id.tagLayout)
    public LinearLayout tagLayout;
    @Bind(R.id.service_name)
    public TextView serviceName;
    @Bind(R.id.author_info)
    public TextView authorInfo;
    @Bind(R.id.service_info)
    public TextView serviceInfo;
    @Bind(R.id.author_img)
    public CircleImageView authorImg;
    @Bind(R.id.like_img)
    public ImageView likeImg;

    @Bind(R.id.verifiedView)
    public ImageView verifiedView;

    private FavAnimation mFavAnimation;

    private RecommendTravelTrip mTrip;
    public static final String VERIFIED_VIEW_SHOW ="1";

    public TravelTripHolderView(Context context) {
        super(context, R.layout.ct_travel_trip_item);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        IntentFilter filter = new IntentFilter(FavoriteListFragment.FAV_CHANGED_ACTION);
        getContext().registerReceiver(mReceiver, filter);
        if (mFavAnimation == null) {
            mFavAnimation = new FavAnimation(((Activity) getContext()).getWindow()) {
                @Override
                public int getTextResource() {
                    return R.string.fav_full_icon;
                }
            };
            mFavAnimation.attach();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        getContext().unregisterReceiver(mReceiver);
        if (mFavAnimation != null) {
            mFavAnimation.detach();
        }
    }

    @Override
    public void initView(View rootView) {
        this.setClickable(true);
        ButterKnife.bind(this);
    }

    private List<String> cardList = new ArrayList<>();

    public void setCurrentList(List<String> cards) {
        this.cardList = cards;
    }

    private int page = 0;


    public void setPage(int page) {
        this.page = page;
    }


    @Override
    public void bindData(final IAdapterData data, final int position) {
        if (data instanceof RecommendTravelTrip) {
            mTrip = (RecommendTravelTrip) data;
            ImageHelper.displayPersonImage(mTrip.getHeadPic(), authorImg, null);
            ImageHelper.displayCtImage(mTrip.getServicePicUrl(), serviceImg, ImageHelper.getCardFourThreeImageOptions());
            String idCheckStatus = mTrip.getIdCheckStatus();
            if (VERIFIED_VIEW_SHOW.equals(idCheckStatus)){
                verifiedView.setImageDrawable(ResourceManager.getDrawable(DrawableClass.VeritifiedSmallDrawable));
                verifiedView.setVisibility(View.VISIBLE);
            }else{
                verifiedView.setVisibility(View.GONE);
            }
            serviceName.setText(mTrip.getServiceName());
            authorInfo.setText(Utils.mergeStrings(new String[]{mTrip.getUserNick(), mTrip.getCareer()}, " · "));
            String price = PriceProxy.getInstance().priceFormatText(mTrip.getPriceType(), mTrip.getShowCurrency(), mTrip.getShowPrice());
            String time = null;
            int hours = mTrip.getServiceTime();
            if (hours > 0) {
                time = getResources()
                        .getString(
                                hours == 1 ? R.string.trip_attribute_duration_value_one : R.string.trip_attribute_duration_value_more
                                , hours);
            }
            String serviceInfoString = Utils.mergeStrings(new String[]{price, time, mTrip.getServiceAddress()}, " · ");
            SpannableStringBuilder ssb = new SpannableStringBuilder(serviceInfoString);
            ssb.setSpan(new ForegroundColorSpan(ResourceUtil.getThemeColor()), 0, price.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            serviceInfo.setText(ssb);
            FavProxy.getInstance().updateFavIcon(likeImg, mTrip.isLiked());

            //GA 统计浏览数
            Product product = new Product()
                    .setId(mTrip.getSid())
                    .setName(mTrip.getServiceName())
                    .setPosition(position);

            HitBuilders.ScreenViewBuilder builder = new HitBuilders.ScreenViewBuilder()
                    .addImpression(product, "Search Results");
            Tracker t = MainApplication.getInstance().getDefaultTracker();
            t.setScreenName("searchResults");
            t.send(builder.build());

            tagLayout.removeAllViews();
            List<Label> labels = mTrip.getLabelList();
            for (int i = 0; labels != null && i < labels.size(); i++) {
                LabelView labelView = new LabelView(tagLayout.getContext());
                Label label = labels.get(i);
                labelView.setLabel(label);
                LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                ll.rightMargin = Utils.dp2pixel(8);
                labelView.setLayoutParams(ll);
                tagLayout.addView(labelView);
            }
            likeImg.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!LoginInstance.getInstance().isLogin() && getContext() instanceof Activity) {
                        LoginProxy.getInstance().gotoUserEnter((Activity) getContext());
                        return;
                    }
                    if (mTrip.isLiked()) {
                        mTrip.setIsLike(0);
                        FavProxy.getInstance().updateFavIcon(likeImg, mTrip.isLiked());
                        FavProxy.getInstance().unFavTrip(mTrip.getSid(), new FavProxy.Callback() {
                            @Override
                            public void onSuccess() {
                            }

                            @Override
                            public void onFail(String message) {
                                mTrip.setIsLike(1);
                                FavProxy.getInstance().updateFavIcon(likeImg, mTrip.isLiked());
                                MessageUtils.showToast(message);
                            }
                        });
                        List<String> ids = new ArrayList<String>();
                        TrackProxy.getInstance().operationAction(TrackBusiness.Source.SERVICE_LIST, TrackBusiness.Action.DISLIKE, String.valueOf(page), TrackProxy.getInstance().getCurrentPageIndex(TravelTripListFragment.PAGE_SIZE, position), ids);
                    } else {
                        if (mFavAnimation != null) {
                            mFavAnimation.show(likeImg);
                        }
                        mTrip.setIsLike(1);
                        FavProxy.getInstance().updateFavIcon(likeImg, mTrip.isLiked());
                        FavProxy.getInstance().favTrip(mTrip.getSid(), mTrip.getServiceName(), mTrip.getServiceAddress(), mTrip.getServicePicUrl(),
                                mTrip.getInsiderId(), mTrip.getUserNick(), mTrip.getHeadPic(), mTrip.getCareer(), new FavProxy.Callback() {
                                    @Override
                                    public void onSuccess() {


                                    }

                                    @Override
                                    public void onFail(String message) {
                                        mTrip.setIsLike(0);
                                        FavProxy.getInstance().updateFavIcon(likeImg, mTrip.isLiked());
                                        MessageUtils.showToast(message);
                                    }
                                });
                        List<String> ids = new ArrayList<String>();
                        TrackProxy.getInstance().operationAction(TrackBusiness.Source.SERVICE_LIST, TrackBusiness.Action.ADDLIKE, String.valueOf(page), TrackProxy.getInstance().getCurrentPageIndex(TravelTripListFragment.PAGE_SIZE, position), ids);
                    }
                }
            });

            setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    //GA 产品点击统计
                    Product product = new Product()
                            .setId(mTrip.getSid())
                            .setName(mTrip.getServiceName())
                            .setPosition(position);
                    ProductAction productAction = new ProductAction(ProductAction.ACTION_CLICK)
                            .setProductActionList("Search Results");
                    HitBuilders.ScreenViewBuilder builder = new HitBuilders.ScreenViewBuilder()
                            .addProduct(product)
                            .setProductAction(productAction);
                    Tracker t = MainApplication.getInstance().getDefaultTracker();
                    t.setScreenName("searchResults");
                    t.send(builder.build());

                    ServiceDetailActivity.start(getContext(),mTrip.getSid());
                    TrackProxy.getInstance().operationAction(TrackBusiness.Source.SERVICE_LIST, TrackBusiness.Action.CLICK, String.valueOf(page), TrackProxy.getInstance().getCurrentPageIndex(TravelTripListFragment.PAGE_SIZE, position), cardList);
                }
            });
        }
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (FavoriteListFragment.FAV_CHANGED_ACTION.equals(intent.getAction())) {
                if (intent.hasExtra(TravelTrip.KEY_TRAVEL_TRIP_ID)){
                    String sid = intent.getStringExtra(TravelTrip.KEY_TRAVEL_TRIP_ID);
                    boolean value = intent.getBooleanExtra(FavoriteListFragment.FAV_CHANGED_VALUE_KEY, false);
                    if (sid.equals(mTrip.getSid())){
                        mTrip.setIsLike(value ? 1 : 0);
                        FavProxy.getInstance().updateFavIcon(likeImg, mTrip.isLiked());
                    }
                }
            }
        }
    };


}
